package com.qf.service;

import com.qf.constant.CacheConstants;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * author:z
 * time:2021/12/29 11:53
 * description:责任链管理者实现类，这里实现具体的策略执行顺序，
 * 以及哪些策略执行，哪些策略不执行的控制操作
 */
@Service
@Slf4j
public class FilterChainManagerImpl implements FilterChainManager{

    /*
    注入所有的策略实现类对象
    key：策略名称
    value：策略实现类对象
     */
    @Autowired
    private Map<String,FilterChainService> filterChainServiceMap;

    @Autowired
    private CacheFeign cacheFeign;
    @Override
    public boolean executeFilter(StandardSubmit standardSubmit) {
        //1.获取redis中的client对象
        Map<String,String> clientMap = cacheFeign.hMGet(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID());
        //2.获取客户对象中需要执行的策略名称以及顺序字符串
        String filtersStr = clientMap.get("filters");
        //3.对策略字符串进行切割得到需要执行的策略名称数组
        String[] filtersArray = filtersStr.split(",");
        //4.遍历策略名称数组
        if(filtersArray!=null){
            for (String filterName : filtersArray) {
                //5.在遍历过程中，根据策略名称获取策略实现类对象
                FilterChainService filterChainService = filterChainServiceMap.get(filterName);
                //6.执行策略方法
                boolean flag = filterChainService.strategy(standardSubmit);
                //7.判断策略执行结果，如果执行失败，跳出循环
                if(!flag){
                    log.info("[策略模块-责任链管理者实现]策略设置执行失败，策略名称={}，standardSubmit={}",filterName,standardSubmit);
                    break;
                }
            }
        }
        return true;
    }
}
